/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.document.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.mapper.query.NativeQuery;
import com.je.common.base.service.MetaResourceService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.document.exception.DocumentException;
import com.je.document.exception.DocumentExceptionEnum;
import com.je.document.model.FileBO;
import com.je.document.service.DocumentBusService;
import com.je.document.service.DocumentOpenService;
import com.je.servicecomb.InputstreamContentTypePart;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DocumentOpenServiceImpl implements DocumentOpenService {
    @Autowired
    private DocumentBusService documentBusService;

    @Autowired
    private MetaResourceService metaResourceService;

    @Override
    public ResponseEntity<InputStream> getThumbnailPicture(String code, String fileKeyParam) {
        InputStream inputStream = documentBusService.thumbnail(fileKeyParam);
        try {
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(inputStream.available()))
                    .header(HttpHeaders.CONTENT_TYPE, "image/jpeg")
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=缩略图.jpg")
                    .body(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ResponseEntity<InputStream> getOriginalPicture(String code, String fileKeyPath) {
        /**
         * 检查filekey是否属于当前方案
         */
        checkFileKey(code, fileKeyPath);
        //获取文件信息
        FileBO fileBO = documentBusService.previewFile(fileKeyPath, null);
        if (fileBO == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        String fileName;
        try {
            fileName = URLEncoder.encode(fileBO.getRelName(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            fileName = "未知文件.txt";
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, fileBO.getContentType())
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
                .body(fileBO.getFile());
    }

    @Override
    public ResponseEntity<InputStream> getAppOriginalPicture(String code, String fileKeyPath) {
        /**
         * 检查filekey是否属于当前app
         */
        checkAppFileKey(code, fileKeyPath);
        //获取文件信息
        FileBO fileBO = documentBusService.previewFile(fileKeyPath, null);
        if (fileBO == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        }
        String fileName;
        try {
            fileName = URLEncoder.encode(fileBO.getRelName(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            fileName = "未知文件.txt";
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, fileBO.getContentType())
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName)
                .body(fileBO.getFile());
    }

    @Override
    public ResponseEntity<Part> getAppPreviewPicture(HttpServletRequest request, String code, String fileKeyParam) {
        /**
         * 检查filekey是否属于当前app
         */
        checkAppFileKey(code, fileKeyParam);

        return documentBusService.previewAndDownload(request, fileKeyParam, fileKeyParam);
    }

    private void checkAppFileKey(String code, String fileKeyPath) {
        DynaBean dynaBean = metaResourceService.selectOneByNativeQuery("JE_META_APPS", NativeQuery.build().eq("APPS_APPID", code));
        List<String> list = new ArrayList<>();
        //应用图标
        list.add(getFileKeyFromJson(dynaBean.getStr("APPS_YYTB")));
        //登录logo
        list.add(getFileKeyFromJson(dynaBean.getStr("APPS_DLLOGO")));
        if (!list.contains(fileKeyPath)) {
            throw new DocumentException("图片不存在或无权访问", DocumentExceptionEnum.DOCUMENT_ERROR);
        }
    }

    private void checkFileKey(String code, String fileKeyPath) {
        DynaBean dynaBean = metaResourceService.selectOneByNativeQuery("JE_CORE_SETPLAN", NativeQuery.build().eq("JE_SYS_PATHSCHEME", code));
        List<String> list = new ArrayList<>();
        list.add(getFileKeyFromJson(dynaBean.getStr("JE_SYS_BACKGROUNDLOGO")));
        list.add(getFileKeyFromJson(dynaBean.getStr("JE_SYS_LEFTIMG")));
        list.add(getFileKeyFromJson(dynaBean.getStr("JE_SYS_ICON")));
        list.add(getFileKeyFromJson(dynaBean.getStr("JE_SYS_TITLELOGO")));
        if (!list.contains(fileKeyPath)) {
            throw new DocumentException("图片不存在或无权访问", DocumentExceptionEnum.DOCUMENT_ERROR);
        }
    }

    private String getFileKeyFromJson(String str) {
        if (StringUtil.isNotEmpty(str)) {
            Object o = JSON.parse(str);
            JSONObject jsonObject = new JSONObject();
            if (o instanceof JSONObject) {
                jsonObject = (JSONObject) o;
            }

            if (o instanceof JSONArray) {
                JSONArray jsonArray = JSON.parseArray(str);
                jsonObject = jsonArray.getJSONObject(0);
            }
            return jsonObject.getString("fileKey");
        }
        return null;
    }
}
